package com.meiya.hugegraph.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.hugegraph.driver.GremlinManager;
import org.apache.hugegraph.structure.constant.Direction;
import org.apache.hugegraph.structure.graph.Edge;
import org.apache.hugegraph.structure.graph.Path;
import org.apache.hugegraph.structure.graph.Vertex;
import org.apache.hugegraph.structure.gremlin.Result;
import org.apache.hugegraph.structure.gremlin.ResultSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.meiya.hugegraph.api.HugeGraphManager;
import com.meiya.hugegraph.config.HugeGraphConfig;
import com.meiya.hugegraph.entity.vo.BatchResult;
import com.meiya.hugegraph.entity.vo.EdgeVO;
import com.meiya.hugegraph.entity.vo.VertexVO;
import com.meiya.hugegraph.util.RestUtil;

/**
 * 交易数据操作服务类
 * 实现交易图数据的各种业务操作
 */
@Service
public class TransactionOperations {

    private static final Logger logger = LoggerFactory.getLogger(TransactionOperations.class);
    private final HugeGraphManager graphManager;
    private final HugeGraphConfig hugeGraphConfig;

    /**
     * 构造函数
     * 
     * @param graphManager HugeGraphManager实例
     * @param hugeGraphConfig HugeGraph配置
     */
    @Autowired
    public TransactionOperations(HugeGraphManager graphManager, HugeGraphConfig hugeGraphConfig) {
        this.graphManager = graphManager;
        this.hugeGraphConfig = hugeGraphConfig;
    }

    /**
     * 创建银行卡顶点
     *
     * @param cardNumber 卡号
     * @param holderName 持卡人姓名
     * @return 创建的顶点
     */
    public Vertex createCardVertex(String cardNumber, String holderName) {
        Map<String, Object> properties = new HashMap<>();
        properties.put("cardNumber", cardNumber);
        properties.put("holderName", holderName);

        return graphManager.addVertex("card", properties);
    }

    /**
     * 创建交易边
     *
     * @param sourceCardId 源卡ID
     * @param targetCardId 目标卡ID
     * @param amount       交易金额
     * @param transTime    交易时间
     * @param ukey         交易唯一标识
     * @return 创建的边
     */
    public Edge createTransactionEdge(Object sourceCardId, Object targetCardId,
            double amount, Date transTime, String ukey) {
        Map<String, Object> properties = new HashMap<>();
        properties.put("amount", amount);
        properties.put("transTime", transTime);
        properties.put("ukey", ukey);

        return graphManager.addEdge(sourceCardId, targetCardId, "transaction", properties);
    }

    /**
     * 查询持卡人的卡
     * 
     * @param holderName 持卡人姓名
     * @param limit      限制数量
     * @return 卡顶点列表
     */
    public List<Vertex> getCardsByHolder(String holderName, int limit) {
        Map<String, Object> properties = new HashMap<>();
        properties.put("holderName", holderName);
        return graphManager.listVertices("card", properties, limit);
    }

    /**
     * 获取所有银行卡或按条件筛选
     * 
     * @param holderName 持卡人姓名（可选）
     * @param limit      限制数量
     * @return 卡顶点列表
     */
    public List<Vertex> getCards(String holderName, int limit) {
        if (holderName != null && !holderName.isEmpty()) {
            return getCardsByHolder(holderName, limit);
        } else {
            return graphManager.listVertices("card", null, limit);
        }
    }

    /**
     * 获取与顶点相连的交易边
     *
     * @param vertexId  顶点ID
     * @param direction 方向
     * @param labels    边标签列表
     * @param limit     限制数量
     * @return 与顶点相连的边列表
     */
    public List<Edge> getTransactionsOfVertex(Object vertexId, Direction direction,
            List<String> labels, int limit) {
        return graphManager.getEdgesOfVertex(vertexId, direction, labels, limit);
    }

    /**
     * 查询金额大于等于指定值的交易
     *
     * @param minAmount 最小金额
     * @param limit     限制数量
     * @return 交易边列表
     */
    public List<Edge> getTransactionsAboveAmount(double minAmount, int limit) {
        Map<String, Object> properties = new HashMap<>();
        properties.put("amount", "P.gte(" + minAmount + ")");
        return graphManager.listEdges("transaction", properties, limit);
    }

    /**
     * 获取所有交易或按金额筛选
     * 
     * @param minAmount 最小金额（可选）
     * @param limit     限制数量
     * @return 交易边列表
     */
    public List<Edge> getTransactions(Double minAmount, int limit) {
        if (minAmount != null && minAmount > 0) {
            return getTransactionsAboveAmount(minAmount, limit);
        } else {
            return graphManager.listEdges("transaction", null, limit);
        }
    }

    /**
     * 批量上传交易数据
     * 
     * @param file CSV文件
     * @return 批量处理结果
     * @throws IOException 文件处理异常
     */
    public BatchResult uploadTransactionData(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("请选择要上传的文件");
        }

        BatchResult result = new BatchResult();
        long startTime = System.currentTimeMillis();
        logger.info("开始批量上传交易数据...");

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
                CSVParser csvParser = CSVFormat.DEFAULT.builder().setHeader().build().parse(reader)) {

            // 1. 先处理卡顶点数据
            Map<String, Object> cardIdMap = new HashMap<>();
            Set<String> processedCards = new HashSet<>();
            List<Map<String, Object>> vertices = new ArrayList<>();

            logger.info("第一阶段：开始处理卡顶点数据...");
            long vertexStartTime = System.currentTimeMillis();

            for (CSVRecord record : csvParser) {
                // 处理源卡
                String sourceCardNumber = record.get("jykh");
                String sourceHolderName = record.get("jyhm");

                if (!processedCards.contains(sourceCardNumber)) {
                    Map<String, Object> vertexData = new HashMap<>();
                    vertexData.put("label", "card");

                    Map<String, Object> properties = new HashMap<>();
                    properties.put("cardNumber", sourceCardNumber);
                    properties.put("holderName", sourceHolderName);

                    vertexData.put("properties", properties);
                    vertices.add(vertexData);
                    processedCards.add(sourceCardNumber);
                }

                // 处理目标卡
                String targetCardNumber = record.get("dskh");
                String targetHolderName = record.get("dshm");
                
                if (!processedCards.contains(targetCardNumber)) {
                    Map<String, Object> vertexData = new HashMap<>();
                    vertexData.put("label", "card");
                    
                    Map<String, Object> properties = new HashMap<>();
                    properties.put("cardNumber", targetCardNumber);
                    properties.put("holderName", targetHolderName);
                    
                    vertexData.put("properties", properties);
                    vertices.add(vertexData);
                    processedCards.add(targetCardNumber);
                }
                
                // 每批处理的顶点数量
                int vertexBatchSize = hugeGraphConfig.getBatch().getVertexBatchSize();
                if (vertices.size() >= vertexBatchSize) {
                    List<String> ids = batchAddVerticesViaRestApi(vertices);
                    
                    // 更新卡号到ID的映射
                    for (int i = 0; i < vertices.size() && i < ids.size(); i++) {
                        Map<String, Object> vertexData = vertices.get(i);
                        Map<String, Object> properties = (Map<String, Object>) vertexData.get("properties");
                        String cardNumber = (String) properties.get("cardNumber");
                        cardIdMap.put(cardNumber, ids.get(i));
                    }
                    
                    vertices.clear();
                }
            }

            // 插入剩余的顶点数据
            if (!vertices.isEmpty()) {
                List<String> ids = batchAddVerticesViaRestApi(vertices);

                // 更新卡号到ID的映射
                for (int i = 0; i < vertices.size() && i < ids.size(); i++) {
                    Map<String, Object> vertexData = vertices.get(i);
                    Map<String, Object> properties = (Map<String, Object>) vertexData.get("properties");
                    String cardNumber = (String) properties.get("cardNumber");
                    cardIdMap.put(cardNumber, ids.get(i));
                }
            }

            long vertexEndTime = System.currentTimeMillis();
            logger.info("顶点数据处理完成，共处理{}个卡顶点，耗时{}毫秒",
                    processedCards.size(), (vertexEndTime - vertexStartTime));

            // 2. 处理交易边数据
            logger.info("第二阶段：开始处理交易边数据...");
            long edgeStartTime = System.currentTimeMillis();

            // 重置解析器，从头开始读取CSV
            reader.close();
            try (BufferedReader newReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
                    CSVParser newCsvParser = CSVFormat.DEFAULT.builder().setHeader().build().parse(newReader)) {

                List<Map<String, Object>> edges = new ArrayList<>();
                int totalTransactions = 0;
                int errorCount = 0;

                for (CSVRecord record : newCsvParser) { 
                    totalTransactions++;

                    String sourceCardNumber = record.get("jykh");
                    String targetCardNumber = record.get("dskh");

                    if (!cardIdMap.containsKey(sourceCardNumber) || !cardIdMap.containsKey(targetCardNumber)) {
                        logger.warn("源卡或目标卡不存在: {}, {}", sourceCardNumber, targetCardNumber);
                        errorCount++;
                        continue;
                    }

                    Map<String, Object> edgeData = new HashMap<>();
                    edgeData.put("label", "transaction");
                    edgeData.put("outV", cardIdMap.get(sourceCardNumber));
                    edgeData.put("inV", cardIdMap.get(targetCardNumber));
                    edgeData.put("outVLabel", "card");
                    edgeData.put("inVLabel", "card");

                    Map<String, Object> properties = new HashMap<>();
                    // 解析交易金额
                    double amount = Double.parseDouble(record.get("jyje"));
                    properties.put("amount", amount);

                    // 解析交易时间
                    String transTimeStr = record.get("jysj");
                    Date transTime;
                    try {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        transTime = dateFormat.parse(transTimeStr);
                    } catch (ParseException e) {
                        logger.warn("交易时间格式错误: {}", transTimeStr);
                        transTime = new Date(); // 使用当前时间作为默认值
                    }
                    properties.put("transTime", transTime);

                    // 交易唯一标识
                    String ukey = record.get("ukey");
                    properties.put("ukey", ukey);

                    edgeData.put("properties", properties);
                    edges.add(edgeData);
                    
                    // 每批处理的边数量
                    int edgeBatchSize = hugeGraphConfig.getBatch().getEdgeBatchSize();
                    if (edges.size() >= edgeBatchSize) {
                        batchAddEdgesViaRestApi(edges);
                        edges.clear();
                    }
                }

                // 插入剩余的边数据
                if (!edges.isEmpty()) {
                    batchAddEdgesViaRestApi(edges);
                }

                long edgeEndTime = System.currentTimeMillis();
                logger.info("边数据处理完成，共处理{}个交易边，耗时{}毫秒",
                        (totalTransactions - errorCount), (edgeEndTime - edgeStartTime));

                // 设置结果
                result.setTotalProcessed(totalTransactions);
                result.setSuccessCount(totalTransactions - errorCount);
                result.setErrorCount(errorCount);
            }

            long endTime = System.currentTimeMillis();
            logger.info("批量上传交易数据完成，总耗时{}毫秒", (endTime - startTime));

            return result;
        }
    }

    /**
     * 使用原生Java API批量上传交易数据
     * 
     * @param file CSV文件
     * @return 批量处理结果
     * @throws IOException 文件处理异常
     */
    public BatchResult uploadTransactionDataNative(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("请选择要上传的文件");
        }

        BatchResult result = new BatchResult();
        long startTime = System.currentTimeMillis();
        logger.info("开始使用原生Java API批量上传交易数据...");

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
                CSVParser csvParser = CSVFormat.DEFAULT.builder().setHeader().build().parse(reader)) {

            // 1. 准备批量顶点和边数据
            List<Vertex> vertices = new ArrayList<>();
            List<Edge> edges = new ArrayList<>();
            Map<String, Vertex> cardMap = new HashMap<>();
            Set<String> processedCards = new HashSet<>();
            int totalRecords = 0;

            logger.info("第一阶段：准备交易数据（原生Java API）...");

            // 设置批处理大小，从配置中获取
            final int vertexBatchSize = hugeGraphConfig.getBatch().getVertexBatchSize();
            final int edgeBatchSize = hugeGraphConfig.getBatch().getEdgeBatchSize();
            int vertexBatchCount = 0;
            int edgeBatchCount = 0;
            int vertexTotal = 0;
            int edgeTotal = 0;
            int errorCount = 0;

            for (CSVRecord record : csvParser) {
                totalRecords++;
                try {
                    // 处理源卡
                    String sourceCardNumber = record.get("jykh");
                    String sourceHolderName = record.get("jyhm");

                    // 创建源卡顶点
                    Vertex sourceVertex;
                    if (!processedCards.contains(sourceCardNumber)) {
                        sourceVertex = new Vertex("card")
                                .property("cardNumber", sourceCardNumber)
                                .property("holderName", sourceHolderName);
                        vertices.add(sourceVertex);
                        cardMap.put(sourceCardNumber, sourceVertex);
                        processedCards.add(sourceCardNumber);
                        
                        // 当顶点数量达到批处理阈值时执行批量添加
                        if (vertices.size() >= vertexBatchSize) {
                            vertexBatchCount++;
                            List<Vertex> addedVertices = graphManager.getGraphManager().addVertices(vertices);
                            vertexTotal += addedVertices.size();
                            logger.debug("完成第{}批顶点添加，本批数量: {}", vertexBatchCount, addedVertices.size());
                            vertices.clear();
                        }
                    } else {
                        sourceVertex = cardMap.get(sourceCardNumber);
                    }

                    // 处理目标卡
                    String targetCardNumber = record.get("dskh");
                    String targetHolderName = record.get("dshm");

                    // 创建目标卡顶点
                    Vertex targetVertex;
                    if (!processedCards.contains(targetCardNumber)) {
                        targetVertex = new Vertex("card")
                                .property("cardNumber", targetCardNumber)
                                .property("holderName", targetHolderName);
                        vertices.add(targetVertex);
                        cardMap.put(targetCardNumber, targetVertex);
                        processedCards.add(targetCardNumber);
                        
                        // 当顶点数量达到批处理阈值时执行批量添加
                        if (vertices.size() >= vertexBatchSize) {
                            vertexBatchCount++;
                            List<Vertex> addedVertices = graphManager.getGraphManager().addVertices(vertices);
                            vertexTotal += addedVertices.size();
                            logger.debug("完成第{}批顶点添加，本批数量: {}", vertexBatchCount, addedVertices.size());
                            vertices.clear();
                        }
                    } else {
                        targetVertex = cardMap.get(targetCardNumber);
                    }

                    // 解析交易金额
                    double amount = Double.parseDouble(record.get("jyje"));

                    // 解析交易时间
                    String transTimeStr = record.get("jysj");
                    Date transTime;
                    try {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        transTime = dateFormat.parse(transTimeStr);
                    } catch (ParseException e) {
                        logger.warn("交易时间格式错误: {}", transTimeStr);
                        transTime = new Date(); // 使用当前时间作为默认值
                    }

                    // 交易唯一标识
                    String ukey = record.get("ukey");

                    // 创建交易边
                    Edge edge = new Edge("transaction")
                            .source(sourceVertex)
                            .target(targetVertex)
                            .property("amount", amount)
                            .property("transTime", transTime)
                            .property("ukey", ukey);
                    edges.add(edge);
                    
                    // 当边数量达到批处理阈值时执行批量添加
                    if (edges.size() >= edgeBatchSize) {
                        edgeBatchCount++;
                        List<Edge> addedEdges = graphManager.getGraphManager().addEdges(edges, false);
                        edgeTotal += addedEdges.size();
                        logger.debug("完成第{}批边添加，本批数量: {}", edgeBatchCount, addedEdges.size());
                        edges.clear();
                    }
                } catch (Exception e) {
                    logger.error("处理记录时发生错误: {}", e.getMessage());
                    errorCount++;
                }
            }

            // 处理剩余的顶点
            if (!vertices.isEmpty()) {
                vertexBatchCount++;
                List<Vertex> addedVertices = graphManager.getGraphManager().addVertices(vertices);
                vertexTotal += addedVertices.size();
                logger.debug("完成第{}批顶点添加，本批数量: {}", vertexBatchCount, addedVertices.size());
                vertices.clear();
            }

            // 处理剩余的边
            if (!edges.isEmpty()) {
                edgeBatchCount++;
                List<Edge> addedEdges = graphManager.getGraphManager().addEdges(edges, false);
                edgeTotal += addedEdges.size();
                logger.debug("完成第{}批边添加，本批数量: {}", edgeBatchCount, addedEdges.size());
                edges.clear();
            }

            long endTime = System.currentTimeMillis();
            logger.info("使用原生Java API批量上传完成，处理记录总数: {}，顶点总数: {}，边总数: {}，错误数: {}，总耗时: {}毫秒", 
                    totalRecords, vertexTotal, edgeTotal, errorCount, (endTime - startTime));

            // 设置结果
            result.setTotalProcessed(totalRecords);
            result.setSuccessCount(totalRecords - errorCount);
            result.setErrorCount(errorCount);

            return result;
        } catch (Exception e) {
            logger.error("使用原生Java API批量上传交易数据失败", e);
            throw new RuntimeException("使用原生Java API批量上传交易数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 通过RESTful API批量添加边
     * 
     * @param edges 边数据列表
     */
    private void batchAddEdgesViaRestApi(List<Map<String, Object>> edges) {
        if (edges == null || edges.isEmpty()) {
            return;
        }

        try {
            long startTime = System.currentTimeMillis();

            // 从配置中获取服务器URL和图名称
            String serverUrl = hugeGraphConfig.getServerUrl();
            String graphName = hugeGraphConfig.getGraphName();
            boolean checkVertex = hugeGraphConfig.getBatch().isCheckVertex();

            // 使用RestUtil进行批量边添加
            RestUtil.batchAddEdges(serverUrl, graphName, edges, checkVertex);

            long endTime = System.currentTimeMillis();
            logger.info("批量添加边完成，数量: {}，耗时: {}毫秒", edges.size(), (endTime - startTime));
        } catch (Exception e) {
            logger.error("批量添加边失败", e);
            throw new RuntimeException("批量添加边失败: " + e.getMessage(), e);
        }
    }

    /**
     * 通过RESTful API批量添加顶点
     * 
     * @param vertices 顶点数据列表
     * @return 创建的顶点ID列表
     */
    private List<String> batchAddVerticesViaRestApi(List<Map<String, Object>> vertices) {
        if (vertices == null || vertices.isEmpty()) {
            return new ArrayList<>();
        }

        try {
            long startTime = System.currentTimeMillis();

            // 从配置中获取服务器URL和图名称
            String serverUrl = hugeGraphConfig.getServerUrl();
            String graphName = hugeGraphConfig.getGraphName();

            // 使用RestUtil进行批量顶点添加
            String response = RestUtil.batchAddVertices(serverUrl, graphName, vertices);

            long endTime = System.currentTimeMillis();
            logger.info("批量添加顶点完成，数量: {}，耗时: {}毫秒", vertices.size(), (endTime - startTime));

            // 解析返回的ID列表
            // 响应格式类似: ["1:marko", "2:ripple"]
            // 这里简化处理，实际项目中应该使用JSON解析库
            List<String> ids = new ArrayList<>();
            if (response != null && !response.isEmpty()) {
                // 去除首尾的 [ 和 ]
                String content = response.substring(1, response.length() - 1);
                // 按逗号分割
                String[] idArray = content.split(",");
                for (String id : idArray) {
                    // 去除引号和空格
                    ids.add(id.trim().replace("\"", ""));
                }
            }

            return ids;
        } catch (Exception e) {
            logger.error("批量添加顶点失败", e);
            throw new RuntimeException("批量添加顶点失败: " + e.getMessage(), e);
        }
    }

    /**
     * 转换Vertex为VO对象
     * 
     * @param vertices 顶点列表
     * @return VO对象列表
     */
    public List<VertexVO> convertVerticesToVO(List<Vertex> vertices) {
        List<VertexVO> result = new ArrayList<>();
        for (Vertex vertex : vertices) {
            VertexVO vo = new VertexVO();
            vo.setId(vertex.id().toString());
            vo.setLabel(vertex.label());
            vo.setProperties(vertex.properties());
            result.add(vo);
        }
        return result;
    }

    /**
     * 转换Edge为VO对象
     * 
     * @param edges 边列表
     * @return VO对象列表
     */
    public List<EdgeVO> convertEdgesToVO(List<Edge> edges) {
        List<EdgeVO> result = new ArrayList<>();
        for (Edge edge : edges) {
            EdgeVO vo = new EdgeVO();
            vo.setId(edge.id().toString());
            vo.setLabel(edge.label());
            vo.setSourceId(edge.sourceId().toString());
            vo.setTargetId(edge.targetId().toString());
            vo.setProperties(edge.properties());
            result.add(vo);
        }
        return result;
    }

    /**
     * 根据卡号集合查询相关交易
     *
     * @param cardNumbers 卡号集合
     * @param hop         跳数
     * @param limit       限制条数
     * @return 查询结果
     */
    public Map<String, Object> searchTransactionsByCards(List<String> cardNumbers, int hop, int limit) {
        long startTime = System.currentTimeMillis();
        logger.info("开始根据卡号集合查询交易数据...");

        Map<String, Object> result = new HashMap<>();
        List<VertexVO> vertices = new ArrayList<>();
        List<EdgeVO> edges = new ArrayList<>();

        try {
            // 将卡号集合转换为格式化字符串: 'card1', 'card2', 'card3'
            String cardNumbersStr = cardNumbers.stream()
                .map(card -> String.format("'%s'", card))
                .collect(Collectors.joining(", "));
            
            // 构建高效的Gremlin查询字符串，参考官方示例
            String gremlinQuery = String.format(
                "g.V().hasLabel('card').has('cardNumber', within(%s)).as('start')" +
                ".repeat(outE('transaction').as('e').inV().as('v') ).times(%d)" +
                ".where(hasLabel('card').has('cardNumber', within(%s)))" +
                ".path().by(identity()).by(identity()).limit(%d)",
                cardNumbersStr, hop, cardNumbersStr, limit
            );
            
            logger.info("执行Gremlin查询: {}", gremlinQuery);

            // 执行Gremlin查询
            GremlinManager gremlin = graphManager.getClient().gremlin();
            ResultSet resultSet = gremlin.gremlin(gremlinQuery).execute();

            // 解析结果，提取顶点和边
            Set<String> processedVertexIds = new HashSet<>();
            Set<String> processedEdgeIds = new HashSet<>();

            // 使用官方推荐的 forEachRemaining 方法处理结果集
            resultSet.iterator().forEachRemaining(result1 -> {
                if (result1 == null) return;
                
                Object obj = result1.getObject();
                if (obj instanceof Path) {
                    Path path = (Path) obj;
                    
                    // 输出日志以便调试
                    logger.debug("处理路径: {}", path);
                    
                    // 遍历路径中的所有对象，确保获取边和顶点
                    path.objects().forEach(pathObj -> {
                        if (pathObj instanceof Vertex) {
                            Vertex vertex = (Vertex) pathObj;
                            String id = vertex.id().toString();
    
                            if (!processedVertexIds.contains(id)) {
                                processedVertexIds.add(id);
                                vertices.add(convertToVertexVO(vertex));
                                logger.debug("添加顶点: {}，标签: {}", id, vertex.label());
                            }
                        } else if (pathObj instanceof Edge) {
                            Edge edge = (Edge) pathObj;
                            String id = edge.id().toString();
    
                            if (!processedEdgeIds.contains(id)) {
                                processedEdgeIds.add(id);
                                edges.add(convertToEdgeVO(edge));
                                logger.debug("添加边: {}，标签: {}, 从: {}, 到: {}", 
                                    id, edge.label(), edge.sourceId(), edge.targetId());
                            }
                        } else {
                            logger.debug("路径中未知对象类型: {}", pathObj.getClass().getName());
                        }
                    });
                } else {
                    logger.debug("结果不是路径对象，而是: {}", obj != null ? obj.getClass().getName() : "null");
                }
            });

            long endTime = System.currentTimeMillis();
            logger.info("查询完成，获取到{}个顶点，{}个边，耗时{}毫秒",
                    vertices.size(), edges.size(), (endTime - startTime));

            // 设置返回结果
            result.put("vertices", vertices);
            result.put("edges", edges);
            result.put("totalCount", vertices.size() + edges.size());
            result.put("queryTime", (endTime - startTime));

            return result;

        } catch (Exception e) {
            logger.error("查询交易数据失败", e);
            throw new RuntimeException("查询交易数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 将顶点转换为VO对象
     */
    private VertexVO convertToVertexVO(Vertex vertex) {
        VertexVO vo = new VertexVO();
        vo.setId(vertex.id().toString());
        vo.setLabel(vertex.label());

        Map<String, Object> properties = new HashMap<>();
        vertex.properties().forEach((key, value) -> {
            properties.put(key, value);
        });
        vo.setProperties(properties);

        return vo;
    }

    /**
     * 将边转换为VO对象
     */
    private EdgeVO convertToEdgeVO(Edge edge) {
        EdgeVO vo = new EdgeVO();
        vo.setId(edge.id().toString());
        vo.setLabel(edge.label());
        vo.setSourceId(edge.sourceId().toString());
        vo.setTargetId(edge.targetId().toString());

        Map<String, Object> properties = new HashMap<>();
        edge.properties().forEach((key, value) -> {
            properties.put(key, value);
        });
        vo.setProperties(properties);

        return vo;
    }
}
